<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="900px"
      @closed="close"
    >
      <el-form ref="form" :model="tableformdata">
        <el-form-item>
          <el-table
            v-if="showdata.htlx == 0"
            :data="tableformdata.tabledata"
            :span-method="arraySpanMethod"
            :tablecolumn="tablecolumn"
          >
            <slot v-for="(item, index) in tablecolumn" :key="index">
              <el-table-column
                v-if="item.value == 'je' || item.value == 'bz'"
                :label="item.label"
                :prop="item.value"
              >
                <template #default="scope">
                  <el-input
                    v-if="
                      !(
                        scope.$index == tableformdata.tabledata.length - 2 &&
                        item.value == 'je'
                      )
                    "
                    v-model="tableformdata.tabledata[scope.$index][item.value]"
                  />
                  <div v-else>
                    {{ tableformdata.tabledata[scope.$index][item.value] }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column v-else :label="item.label" :prop="item.value" />
            </slot>
          </el-table>
          <el-table
            v-else-if="showdata.htlx == 1"
            :data="tableformdata.tabledata"
            :span-method="arraySpanMethod1"
            :tablecolumn="tablecolumn1"
          >
            <slot v-for="(item, index) in tablecolumn1" :key="index">
              <el-table-column
                v-if="['rgje', 'bz', 'yjje'].indexOf(item.value) >= 0"
                :label="item.label"
                :prop="item.value"
              >
                <template #default="scope">
                  <div
                    v-if="
                      scope.$index >= tableformdata.tabledata.length - 2 &&
                      item.value != 'bz'
                    "
                  >
                    {{ tableformdata.tabledata[scope.$index][item.value] }}
                  </div>
                  <el-input
                    v-else
                    v-model="tableformdata.tabledata[scope.$index][item.value]"
                  />
                </template>
              </el-table-column>
              <el-table-column v-else :label="item.label" :prop="item.value" />
            </slot>
          </el-table>
          <el-table
            v-else-if="showdata.htlx == 2"
            :data="tableformdata.tabledata"
            :tablecolumn="tablecolumn2"
          >
            <slot v-for="(item, index) in tablecolumn2" :key="index">
              <el-table-column
                v-if="item.value == 'fcbl1' || item.value == 'fcbl2'"
                :label="item.label"
                :prop="item.value"
              >
                <template #default="scope">
                  <el-input
                    v-model="tableformdata.tabledata[scope.$index][item.value]"
                  />
                  <!-- <div v-else>
                    {{ tableformdata.tabledata[scope.$index][item.value] }}
                  </div> -->
                </template>
              </el-table-column>
              <el-table-column v-else :label="item.label" :prop="item.value" />
            </slot>
          </el-table>
        </el-form-item>
      </el-form>

      <zform
        ref="formz"
        colspan="12"
        label-position="left"
        labelwidth="100px"
        :nowdata="formdata"
        :nowinputs="inputs"
      />
      <template #footer>
        <el-button :loading="loading" type="primary" @click="updatafn">
          生成合同
        </el-button>
        <slot name="btnslot"></slot>
        <el-button @click="close">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
  import zform from '@/components/zFrom/zFrom'
  import qs from 'qs'
  import 'docxtemplater/build/docxtemplater.js'
  import 'pizzip/dist/pizzip.js'
  import 'pizzip/dist/pizzip-utils.js'
  import 'file-saver'
  export default {
    name: 'afterlistxjpd',
    components: {
      zform,
    },
    emits: ['edtdatafn'],
    data() {
      return {
        // tablecolumn:[],
        // inputs:
        tablecolumn: [
          { label: '序号', value: 'index' },
          { label: '名称', value: 'mc' },
          { label: '规格', value: 'gg' },
          { label: '单位', value: 'dw', defaultValue: '台' },
          { label: '数量', value: 'sl' },
          { label: '单价', value: 'je' },
          { label: '金额', value: 'jez' },
          { label: '备注', value: 'bz' },
        ],
        tablecolumn1: [
          { label: '序号', value: 'index' },
          { label: '名称', value: 'mc' },
          { label: '规格型号', value: 'gg' },
          { label: '单位', value: 'dw', defaultValue: '台' },
          { label: '数量', value: 'sl' },
          { label: '日供价格', value: 'rgje' },
          { label: '日供金(元/天）', value: 'rgj' },
          { label: '总计', value: 'rgjzj' },
          { label: '押金（元/台）', value: 'yjje' },
          { label: '备注', value: 'bz' },
        ],
        tablecolumn2: [
          // 序号	名称		单位	数量
          { label: '序号', value: 'index' },
          { label: '名称', value: 'mc' },
          { label: '规格型号', value: 'gg' },
          { label: '单位', value: 'dw', defaultValue: '台' },
          { label: '数量', value: 'sl' },
          { label: '分成比例（合作方）', value: 'fcbl1' },
          { label: '分成比例（公司）', value: 'fcbl2' },
        ],
        inputs: [],
        inputs0: [
          { label: '甲方', value: 'firstparty' },
          { label: '合同编号', value: 'number' },
          { label: '综合服务费', value: 'fwf', dw: '元', fl: '100' },
          { label: '姓名', value: 'uxm' },
          { label: '电话', value: 'utel' },
          { label: '地址', value: 'dz' },
          { label: '发货日期', value: 'jhtime', dw: '天之后' },
          { label: '保修时间', value: 'bxtime', dw: '年' },
          { label: '单位全称', value: 'dwqc' },
          { label: '法人代表', value: 'frdb' },
          { label: '开户名', value: 'khm' },
          { label: '开户行', value: 'khh' },
          { label: '帐号', value: 'zh' },
          { label: '税号', value: 'sh' },
        ],
        inputs1: [
          {
            label: '甲方',
            value: 'firstparty1',
            defaultValue: '浙江臻万科技有限公司',
          },
          { label: '主协议编码', value: 'number1' },
          {
            label: '乙方',
            value: 'firstparty2',
          },
          { label: '代理商编码', value: 'number2' },
          {
            label: '物流方式',
            value: 'wlfs',
            defaultValue: '陆运',
          },
          { label: '姓名', value: 'uxm' },
          { label: '电话', value: 'utel' },
          { label: '地址', value: 'dz' },
          { label: '发货日期', value: 'jhtime', dw: '工作日' },

          { label: '单位全称', value: 'dwqc' },
          { label: '法人代表', value: 'frdb' },
          { label: '开户名', value: 'khm' },
          { label: '开户行', value: 'khh' },
          { label: '帐号', value: 'zh' },
          { label: '税号', value: 'sh' },
          { label: '供方代理人', value: 'gfdlr' },
          { label: '电话', value: 'gfdh', defaultValue: '0571-88002912' },
          { label: '需方代理人', value: 'xfdlr' },
          { label: '电话', value: 'xfdh' },
        ],
        inputs2: [
          {
            label: '甲方',
            value: 'firstparty1',
            defaultValue: '浙江臻万科技有限公司',
          },
          { label: '主协议编码', value: 'number1' },
          {
            label: '乙方',
            value: 'firstparty2',
          },
          { label: '代理商编码', value: 'number2' },
          {
            label: '物流方式',
            value: 'wlfs',
            defaultValue: '陆运',
          },
          { label: '姓名', value: 'uxm' },
          { label: '电话', value: 'utel' },
          { label: '地址', value: 'dz' },
          { label: '发货日期', value: 'jhtime', dw: '工作日' },

          { label: '单位全称', value: 'dwqc' },
          { label: '法人代表', value: 'frdb' },
          { label: '开户名', value: 'khm' },
          { label: '开户行', value: 'khh' },
          { label: '帐号', value: 'zh' },
          { label: '税号', value: 'sh' },
          { label: '供方代理人', value: 'gfdlr' },
          { label: '电话', value: 'gfdh', defaultValue: '0571-88002912' },
          { label: '需方代理人', value: 'xfdlr' },
          { label: '电话', value: 'xfdh' },
        ],
        dialogVisible: false,
        title: '详情',

        formdata: {},
        showdata: {},
        tableformdata: {},
        loading: false,
        zt: '',
      }
    },
    computed: {},
    watch: {
      tableformdata: {
        handler(data) {
          if (this.showdata.htlx == 0) {
            let jehj = 0
            if (!data.tabledata) {
              return
            }
            data.tabledata.forEach((e, i) => {
              if (i < data.tabledata.length - 2) {
                let je = Number(e.je)
                if (isNaN(je)) {
                  je = 0
                }
                let jez = Number(je) * Number(e.sl)
                if (e.jez != jez) {
                  this.tableformdata.tabledata[i].jez = jez
                }
                jehj += jez
              }
            })
            if (jehj != data.tabledata[data.tabledata.length - 2].je) {
              this.tableformdata.tabledata[data.tabledata.length - 2].jez = jehj
              this.tableformdata.tabledata[data.tabledata.length - 1].index =
                '人民币大写：' + this.ToString(jehj)
            }
          } else if (this.showdata.htlx == 1) {
            let jehj = 0,
              yjjehj = 0
            if (!data.tabledata) {
              return
            }
            data.tabledata.forEach((e, i) => {
              if (i < data.tabledata.length - 2) {
                let je = Number(e.rgje)
                if (isNaN(je)) {
                  je = 0
                }
                let jez = Number(je) * Number(e.sl)
                if (e.rgjzj != jez) {
                  this.tableformdata.tabledata[i].rgj =
                    Math.ceil((jez / 365) * 100) / 100
                  this.tableformdata.tabledata[i].rgjzj = jez
                }
                jehj += jez
                let yjje = Number(e.yjje)
                if (isNaN(yjje)) {
                  yjje = 0
                }
                let yjjez = Number(yjje) * Number(e.sl)

                yjjehj += yjjez
              }
            })
            if (
              jehj != data.tabledata[data.tabledata.length - 2].rgje ||
              yjjehj != data.tabledata[data.tabledata.length - 2].yjje
            ) {
              this.tableformdata.tabledata[
                data.tabledata.length - 2
              ].rgje = jehj
              this.tableformdata.tabledata[
                data.tabledata.length - 2
              ].yjje = yjjehj
              this.tableformdata.tabledata[data.tabledata.length - 1].index =
                '人民币大写：' + this.ToString(jehj)
            }
          }
        },
        deep: true,
      },
    },
    mounted() {},
    methods: {
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (rowIndex == this.tableformdata.tabledata.length - 2) {
          if (columnIndex == 0) {
            return [1, 6]
          } else if (columnIndex <= 5) {
            return [0, 0]
          }
        } else if (rowIndex == this.tableformdata.tabledata.length - 1) {
          return [1, 7]
        }
      },
      arraySpanMethod1({ row, column, rowIndex, columnIndex }) {
        if (rowIndex == this.tableformdata.tabledata.length - 2) {
          if (columnIndex == 0) {
            return [1, 5]
          } else if (columnIndex <= 4) {
            return [0, 0]
          }
        } else if (rowIndex == this.tableformdata.tabledata.length - 1) {
          if (columnIndex == 0) {
            return [1, 9]
          } else if (columnIndex <= 8) {
            return [0, 0]
          }
        }
      },
      ToString(n) {
        if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) {
          return '数据非法' //判断数据是否大于0
        }

        var unit = '千百拾亿千百拾万千百拾元角分',
          str = ''
        n += '00'

        var indexpoint = n.indexOf('.') // 如果是小数，截取小数点前面的位数

        if (indexpoint >= 0) {
          n = n.substring(0, indexpoint) + n.substr(indexpoint + 1, 2) // 若为小数，截取需要使用的unit单位
        }

        unit = unit.substr(unit.length - n.length) // 若为整数，截取需要使用的unit单位
        for (var i = 0; i < n.length; i++) {
          str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i) //遍历转化为大写的数字
        }

        return str
          .replace(/零(千|百|拾|角)/g, '零')
          .replace(/(零)+/g, '零')
          .replace(/零(万|亿|元)/g, '$1')
          .replace(/(亿)万|壹(拾)/g, '$1$2')
          .replace(/^元零?|零分/g, '')
          .replace(/元$/g, '元整') // 替换掉数字里面的零字符，得到结果
      },
      async show(data = {}, zt, asynccallback) {
        let formdata = this.$z.deepClone(data)

        this.showdata = this.$z.deepClone(data)

        this.inputs = this[`inputs${this.showdata.htlx}`]
        let par1 = qs.parse(formdata.par1)

        this.zt = zt
        this.title = '合同'
        if (par1.ShopUserwpgmDetailed) {
          this.tabledata = this.$z.deepClone(par1.ShopUserwpgmDetailed)
        } else {
          this.tabledata = formdata.ddxq.map((e, i) => {
            return {
              index: i + 1,
              mc: e.ShopUserwp.mc,
              sl: e.ShopUserwpgmDetailed.sl,
              gg: e.ShopUserwpgmDetailed.gg,
              dw: '台',
              jez: '',
              bz: '',
            }
          })
        }
        if (this.showdata.htlx == '0') {
          if (par1.ShopUserwpgmDetailed) {
            this.tabledata.push(
              {
                index: '合计（含税）：小写',
                jez: par1.jehj,
                bz: par1.bzhj,
              },
              {
                index: par1.jedx,
              }
            )
          } else {
            this.tabledata.push(
              {
                index: '合计（含税）：小写',
                je: '',
                bz: '',
              },
              {
                index: '人民币大写：',
              }
            )
          }
        } else if (this.showdata.htlx == '1') {
          if (par1.ShopUserwpgmDetailed) {
            this.tabledata.push(
              {
                index: '合计（含税）：小写',
                rgj: '押金合计 ',
                yjje: par1.yjjehj,
                rgje: par1.rgjehj,
                bz: par1.bzhj,
              },
              {
                index: par1.jedx,
                bz: par1.bzhj2,
              }
            )
          } else {
            this.tabledata.push(
              {
                index: '合计（含税）：小写',
                rgj: '押金合计 ',
                yjje: '',
                rgje: '',
                bz: '',
              },
              {
                index: '人民币大写：',
                bz: '',
              }
            )
          }
        }

        delete par1.ShopUserwpgmDetailed
        let zdata = {
          uxm: formdata.uxm,
          utel: formdata.utel,
          dz: formdata.dzsh,
          ...par1,
        }
        this.tableformdata = { tabledata: this.tabledata }
        this.formdata = zdata
        // this.ggsdata = this.formdata.ggs || []
        this.asynccallback = asynccallback
        this.dialogVisible = true
        // tableformdata.tabledata
        console.log(formdata, this.tabledata)
      },

      async getdata() {
        // sutype:
      },
      async updatafn() {
        this.loading = true
        let formdata = await this.$refs.formz.validate()
        let updata = { ...formdata }
        updata.ShopUserwpgmDetailed = this.tableformdata.tabledata.filter(
          (e, i) => {
            return i < this.tableformdata.tabledata.length - 2
          }
        )
        if (this.showdata.htlx == '2') {
          updata.ShopUserwpgmDetailed = this.tableformdata.tabledata
        } else {
          let jehj = this.tableformdata.tabledata[
            this.tableformdata.tabledata.length - 2
          ].jez
          updata.yjjehj = this.tableformdata.tabledata[
            this.tableformdata.tabledata.length - 2
          ].yjje
          updata.rgjehj = this.tableformdata.tabledata[
            this.tableformdata.tabledata.length - 2
          ].rgje
          updata.bzhj = this.tableformdata.tabledata[
            this.tableformdata.tabledata.length - 2
          ].bz
          updata.bzhj2 = this.tableformdata.tabledata[
            this.tableformdata.tabledata.length - 1
          ].bz
          updata.jehj = jehj
          updata.jedx = this.ToString(jehj)
        }
        if (this.showdata.htlx == '1') {
          updata.jedx = this.ToString(updata.rgjehj)
        }
        let time = this.$z.timefn.gettime()
        updata.yy = time.substr(0, 4)
        updata.mm = time.substr(5, 2)
        updata.dd = time.substr(8, 2)

        this.generate(updata)
        let ShopUserwpgmedtdata = this.$z.deepClone(this.showdata)
        delete ShopUserwpgmedtdata.ddxq
        ShopUserwpgmedtdata.par1 = qs.stringify(updata)
        let { data } = await this.$z.$axios
          .post('/ShopUserwpgmedt', ShopUserwpgmedtdata)
          .catch(() => {
            this.loading = false
          })

        if (this.zt == 0) {
          let par = this.$z.parfn(data)
          if (par.value == 'succeed') {
            this.$message.success(par.label)
          } else {
            this.$message.error(par.label)
          }
          this.dialogVisible = false
        }
        this.loading = false
        this.asynccallback()
      },
      // 导出word
      loadFile(url, callback) {
        PizZipUtils.getBinaryContent(url, callback)
      },
      generate(wordData) {
        var that = this
        this.loadFile(
          `./word/word${this.showdata.htlx}.docx`,
          function (error, content) {
            //url模板存放的位置
            if (error) {
              throw error
            }
            var zip = new PizZip(content)
            var doc = new window.docxtemplater().loadZip(zip)
            doc.setData({
              ...wordData, //导入到模板文档的数据对象
            })
            try {
              // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
              doc.render()
            } catch (error) {
              var e = {
                message: error.message,
                name: error.name,
                stack: error.stack,
                properties: error.properties,
              }
              console.log(
                JSON.stringify({
                  error: e,
                })
              )
              // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
              throw error
            }
            var out = doc.getZip().generate({
              type: 'blob',
              mimeType:
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            }) //Output the document using Data-URI
            let htlxselect = { 0: '买断', 1: '日供', 2: '合作' }
            // this.showdata.htlx0-，1-，2-
            saveAs(
              out,
              `充电桩购销合同（${htlxselect[that.showdata.htlx]}简略）.docx`
            )
          }
        )
      },
      close() {
        this.dialogVisible = false
      },
      openfn() {},
    },
  }
</script>
<style lang="scss">
  .baseflex {
    display: flex;
    align-items: center;
  }
  .useritem {
    height: 40px;
    padding-left: 10px;
    background: rgba(255, 255, 255, 0.1);
    display: flex;
    align-items: center;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;

    &:hover {
      background: rgba(255, 255, 255, 0.2);
    }

    &.active {
      background: rgba(255, 255, 255, 0.2);
    }
  }
  .span12 .el-form-item {
    background: rgba(255, 255, 255, 0.2);
    margin-bottom: 8px;
    padding: 10px;
  }
</style>
